// window.Global = {
//   score = 0,
// };


cc.Class({
    extends: cc.Component,

    properties: {
       //倒计时进度条
       timeProgressBar:cc.ProgressBar,

       //游戏时间文本
       timeLabel : cc.Label,

       //主角节点
        master: cc.Node,

        //地刺预制件
        diciPrefab: cc.Prefab,

        //用于加载地刺的父节点
        diciNodePar: cc.Node,

        //得分
        scoreLable: cc.Label,
    },

   
    onLoad: function () {
        this.highScore = 0;
        this.score = 0;
        this.count = 0;
        this.totalTime = 60;
        this.remainTime = this.totalTime;
        //启动倒计时
        this.schedule(function(){
            this.remainTime--;
            if(this.remainTime >=0){
                this.timeLabel.string = 'time:' + this.remainTime;
                var ratio = this.remainTime / this.totalTime;
                this.timeProgressBar.progress = ratio ;
            }else{
                cc.director.loadScene("over");
            }         

    },1);
    //为屏幕添加触摸事件
    this.node.on('touchstart',this.inputControl.bind(this));


        for(var i=0; i < 8; i++ ){

            this.spawnDici();
        }
    },

    

    //触摸事件回调
    inputControl:function(touch,event){
        //判断点击处于那一侧
        var isClickLeft = touch.getLocation().x < cc.winSize.width / 2;
        //判断主角处于那一侧
        var isInLeft = this.master.x < 0;
        this.onJump(isClickLeft === isInLeft,isInLeft);
        this.spawnDici();

    },  


     addScore:function(){
        this.score++;
        this.scoreLable.string = "score:" + this.score;
        cc.mydata.score = this.score;
    },

 


    //主角跳跃
    onJump:function(isjumpInPlace,isInLefteft){
        var t = isInLefteft ? 1 : -1;
        var isFlipByX = (isInLefteft && !isjumpInPlace) ? 180 : 0;
        var jumpInPlace = cc.sequence(cc.moveBy(0.1,cc.p(50*t,0)),cc.moveBy(0.1,cc.p(-50*t,0)));
        var jumpToOtherSide = cc.spawn(cc.moveBy(0.1,cc.p(460*t,0)),cc.rotateTo(0,0,isFlipByX));
        if(isjumpInPlace){
            this.master.runAction(jumpInPlace);

        }else{
            this.master.runAction(jumpToOtherSide);
        }

    },

    //生成地刺
    spawnDici:function(){
        this.count++;
        var dici = cc.instantiate(this.diciPrefab);
        this.diciNodePar.addChild(dici);
        var isLeft = (Math.random() > 0.5) ? 1 :-1;//确定左右
        var offsetY ;
        if(this.count<9){
            offsetY= 290 - this.count * 140;
        }else{
            offsetY= 290 - 8 * 140;
            }
        dici.x *= isLeft;
        dici.y = offsetY;
        dici.scaleX = isLeft; 

    },



});
